package com.example.april.controller;

import com.alibaba.fastjson.JSON;
import com.example.april.dao.NewCustomerDao;
import com.example.april.pojo.Customer;
import com.example.april.pojo.NewCustomer;
import com.example.april.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class NewUDIController {

    @Autowired
    CustomerService customerService;

    @Autowired
    NewCustomerDao newCustomerDao;

    @RequestMapping("/newIndex")
    public String newIndex(Model model){
        List<NewCustomer> newCustomers = newCustomerDao.selectList(null);
        model.addAttribute("attrs",NewCustomer.attrs);
        model.addAttribute("customers",newCustomers);
        return "newIndex";
    }

    @RequestMapping("addAttrPage")
    public String addAttrPage(Model model){
        String attrs = NewCustomer.attrs.stream().collect(Collectors.joining(","));
        model.addAttribute("attrs",attrs);
        return "addAttr";
    }
    @RequestMapping("addAttr")
    public String addAttrPage(String attrs, Model model){
        NewCustomer.attrs.clear();
        String[] attr = attrs.split(",");
        Collections.addAll(NewCustomer.attrs,attr);
        return "redirect:/newIndex";
    }

    @RequestMapping("/newUpdate")
    public String newUpdate(@RequestParam String id, Model model){
        Customer customer = customerService.update(id);
        model.addAttribute("customer",customer);
        return "/update";
    }
    @GetMapping("/newSubUpdate")
    public String newSubUpdate(Customer customer){
        customerService.subUpdate(customer);
        return "redirect:/index";
    }

    @RequestMapping("/newDelete")
    public String newDelete(@RequestParam String id){
        customerService.delete(id);
        return "redirect:/index";
    }

    @RequestMapping("/newToInsert")
    public String newToInsert(Model model){
        model.addAttribute("attrs",NewCustomer.attrs);
        return "newInsert";
    }
    @RequestMapping("/newInsert")
    public String insert(@RequestParam Map<String,String> params){
        newCustomerDao.insertOne(JSON.toJSONString(params));
        return "redirect:/Index";
    }
}
